import { MessageBox } from 'element-ui'

const defaults = {
  confirmButtonText: '',
  cancelButtonText: '',
  confirmButtonLoading: false
}

/**
 * 注意：必须要在引入 element-ui 后使用该插件
 */
export default {
  install(Vue) {
    function dialogDefaults(args) {
      if (args.length === 1) {
        args.push({ ...defaults })
      }
      if (args.length === 2) {
        args[1] = { ...defaults, ...args[1] }
      }
      if (args.length === 3) {
        args[2] = { ...defaults, ...args[2] }
      }
      return args
    }

    const rawAlert = MessageBox.alert
    if (rawAlert) {
      const proxyFunc = function (...args) {
        const newArgs = dialogDefaults(args)
        return rawAlert(...newArgs)
      }
      if (Vue.prototype.$alert) {
        Vue.prototype.$alert = proxyFunc
      }
      MessageBox.alert = proxyFunc
    }

    const rawPrompt = MessageBox.prompt
    if (rawPrompt) {
      const proxyFunc = function (...args) {
        const newArgs = dialogDefaults(args)
        return rawPrompt(...newArgs)
      }
      if (Vue.prototype.$prompt) {
        Vue.prototype.$prompt = proxyFunc
      }
      MessageBox.prompt = proxyFunc
    }

    const rawConfirm = MessageBox.confirm
    if (rawConfirm) {
      const proxyFunc = function (...args) {
        const newArgs = dialogDefaults(args)
        return rawConfirm(...newArgs)
      }
      if (Vue.prototype.$confirm) {
        Vue.prototype.$confirm = proxyFunc
      }
      MessageBox.confirm = proxyFunc
    }
  }
}
